package com.ihr360.payroll.service.salarytasklet.listener;

import com.ihr360.job.core.BatchStatus;
import com.ihr360.job.core.entity.JobExecution;
import com.ihr360.job.core.listener.JobExecutionListenerSupport;
import com.ihr360.payroll.dao.ActivePayPeriodRepository;
import com.ihr360.payroll.model.dto.salary.task.period.ActivePayPeriod;
import com.ihr360.payroll.model.dto.salary.task.period.PayPeriodTerm;
import com.ihr360.payroll.type.PeriodState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * @author davidwei
 */
@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
    private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class);

    @Autowired
    private ActivePayPeriodRepository activePayPeriodRepository;

    public Long payPeriodId;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        log.info("!!! before JOB ! job status" + jobExecution.getStatus());
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        BatchStatus status = jobExecution.getStatus();
        log.info("!!! after JOB ! job status" + status);
        if (status == BatchStatus.COMPLETED) {
            log.info("!!! JOB FINISHED! Time to verify the results");
        } else {
            ActivePayPeriod one = activePayPeriodRepository.findOne(payPeriodId);
            if (one != null) {
                one.setState(PeriodState.CALCULATED);
                PayPeriodTerm currentTerm = one.getCurrentTerm();
                if (currentTerm != null) {
                    currentTerm.setState(PeriodState.CALCULATED);
                    currentTerm.setTaskExecutionSequence(currentTerm.getTaskExecutionSequence() + 1);
                }
                activePayPeriodRepository.save(one);
                payPeriodId = null;
            }
        }
    }


}